/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bpmlab.shift.dao;

import bpmlab.shift.dao.service.GenericDAO;
import java.lang.reflect.Field;
import java.util.List;
import java.util.logging.Logger;
import javax.persistence.EntityManager;

/**
 *
 * @author Mikael Lima
 * @param <T>
 */
public class GenericDAOJpa<T> implements GenericDAO<T> {

    private final Class<T> clazz;

    public GenericDAOJpa(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public void salvar(T o) throws DAOException {
        try {
            EntityManager em = JpaUtil.getEntityManager();
            if (getId(o) == null || getId(o).equals(0)) {
                em.persist(o);
            } else {
                em.merge(o);
            }
        } catch (Exception e) {
            throw new DAOException(e);
        }
    }

    @Override
    public void excluir(T o) throws DAOException {
        try {
            EntityManager em = JpaUtil.getEntityManager();
            em.remove(em.merge(o));
        } catch (Exception e) {
            throw new DAOException(e);
        }
    }

    @Override
    public T obter(Object id) {
        EntityManager em = JpaUtil.getEntityManager();
        return em.find(clazz, id);
    }

    @Override
    public List<T> obterTodos() {
        EntityManager em = JpaUtil.getEntityManager();
        String query = "select o from " + clazz.getSimpleName() + " o";
        return em.createQuery(query).getResultList();
    }

    private Object getId(Object o) {
        try {
            Field field = o.getClass().getDeclaredField("id");
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            return field.get(o);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
    }
}
